package com.face.server.service;

import com.mongodb.BasicDBObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * Created by ryan on 2018/1/25.
 */
@Service
public class UtileService {
    @Autowired
    GridFsOperations fs;
    public GridFSDBFile getFile(String resourceId) {
        GridFSDBFile mongoFile = fs.findOne(new Query(where("_id").is(resourceId)));
        if (mongoFile == null)
            throw new RuntimeException("文件不存在");
        return mongoFile;
    }

    public String upFile(MultipartFile file) throws IOException {
        GridFSFile reDBObj = fs.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType());
        return reDBObj.getId().toString();
    }

    public ResponseEntity<Resource> getFileStream(String resourceId) throws UnsupportedEncodingException {
        GridFSDBFile mongoFile = fs.findOne(new Query(where("_id").is(resourceId)));
        String filename = "inline; filename=" + URLEncoder.encode(mongoFile.getFilename(), "UTF-8");
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, mongoFile.getContentType())
                .header(HttpHeaders.CONTENT_ENCODING, "UTF-8").header(HttpHeaders.CONTENT_DISPOSITION, filename)
                .cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS))
                .body(new InputStreamResource(mongoFile.getInputStream()));
    }

    public int delete(String id) {
        fs.delete(Query.query(where("_id").is(id)));
        return 1;
    }

    public static boolean isNum(String str){
        for (int i=str.length();--i>=0;){
            int chr=str.charAt(i);
            if (chr<48||chr>57)
                return false;
        }
        return true;
    }

    public static boolean isBool(String str){
        if (str.equals("true")||str.equals("false"))
            return true;
        return false;
    }

}
